package com.zaofan.mobile.controller;

import com.zaofan.bean.Comment;
import com.zaofan.bean.Product;
import com.zaofan.bean.Reply;
import com.zaofan.bean.Shop;
import com.zaofan.cache.CacheManage;
import com.zaofan.constant.UrlConstant;
import com.zaofan.mobile.bean.ProductResult;
import com.zaofan.service.CommentService;
import com.zaofan.service.ProductService;
import com.zaofan.service.ReplyService;
import com.zaofan.service.ShopService;
import com.zaofan.utils.C3p0DataSourceUtils;
import com.zaofan.utils.JsonUtils;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.MapListHandler;

import java.io.IOException;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/mobile/product")
public class ProductController extends BaseServlet {

	private static final long serialVersionUID = 5884947841079014459L;
	private ProductService productService = new ProductService();
	private ShopService shopService = new ShopService();
	private CommentService commentService = new CommentService();
	private ReplyService replyService = new ReplyService();

	/**
	 * 产品详情
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	protected void info(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try {
			String temp = request.getParameter("id");
			int id = Integer.valueOf(temp);
			Product p = productService.findById(id);
			if (p == null) {
				JsonUtils.writeBeanFailJson("参数错误", response);
				return;
			}
			System.err.println("get product info : id = " + id);
			// com.zaofan.mobile.bean.Shop s = new
			// com.zaofan.mobile.bean.Shop();
			// BeanUtils.copyProperties(s, shop);
			JsonUtils.writeSuccessJson("查询成功", p, response);
			return;
		} catch (Exception e) {
			e.printStackTrace();
			JsonUtils.writeBeanFailJson("参数错误", response);
		}
		JsonUtils.writeBeanFailJson("获取失败", response);
	}

	/**
	 * 获取商家产品
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	public void product(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try {
			String temp = request.getParameter("shopId");
			int shopId = Integer.valueOf(temp);
			Shop shop = shopService.findById(shopId);
			if (shop == null) {
				JsonUtils.writeBeanFailJson("商铺信息错误!!", response);
				return;
			}
			if (CacheManage.shopProducts.containsKey(shopId)) {
				JsonUtils.writeSuccessJson("查询成功", CacheManage.shopProducts.get(shopId), response);
				return;
			}
			List<ProductResult> products = productService.findByShopId(shopId);
			if (CacheManage.shopProducts.size() >= 10) {
				CacheManage.shopProducts.remove(CacheManage.shopIds.getFirst());
				CacheManage.shopProducts.put(shopId, products);
				CacheManage.shopIds.addLast(shopId);
			} else {
				CacheManage.shopProducts.put(shopId, products);
				CacheManage.shopIds.addLast(shopId);
			}
			JsonUtils.writeSuccessJson("查询成功", products, response);
		} catch (Exception e) {
			e.printStackTrace();
			JsonUtils.writeBeanFailJson("参数错误!!", response);
		}
		JsonUtils.writeBeanFailJson("查询失败!!", response);
	}

    /**
     * 获取分类产品
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    public void productType(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        QueryRunner qr = new QueryRunner(C3p0DataSourceUtils.getDataSource());
        List<Map<String, Object>> pros = null;
        try {
            String areaId = request.getParameter("areaId");
            String classId = request.getParameter("classId");
            String begin = request.getParameter("begin");
            String end = request.getParameter("end");




            pros = qr.query("select product.id,name,concat('"+UrlConstant.HOST_URL+"',image) as image,categoryId,product.des,product.sdes,product.productClassId," +
                    "concat('"+UrlConstant.HOST_URL+"',bigImage) as bigImage,price,shopId,className,sellcount AS sellcount,concat(productclass.closetime,'') AS closetime "
                    		+ " from product " +
                    "left join shop on shop.id = product.shopId " +
                    "left join productclass on productclass.id = product.productClassId " +
                    "where (shop.cityId = ? or coverType = 1) and productClassId = ? and product.state = 0 and shop.isOpen = 1 and shop.state = 0 order by product.sort asc,product.addtime desc	 limit ?,?",new MapListHandler(),new Object[]{areaId,classId,Integer.valueOf(begin),Integer.valueOf(end)});

			// TODO 酒店注释
//			if(null  != request.getSession().getAttribute("isHotel")){
//				String isHotel =   request.getSession().getAttribute("isHotel").toString();
//				if(isHotel.equals("1")) {
//					pros = qr.query("select product.id,name,concat('"+UrlConstant.HOST_URL+"',hotelImage) as image,categoryId,product.des,product.sdes,product.productClassId," +
//							"concat('"+UrlConstant.HOST_URL+"',bigImage) as bigImage,concat(hotelPrice,'') as price,shopId,className,sellcount AS sellcount,concat(productclass.closetime,'') AS closetime "
//							+ " from product " +
//							"left join shop on shop.id = product.shopId " +
//							"left join productclass on productclass.id = product.productClassId " +
//							"where (shop.cityId = ? or coverType = 1) and productClassId = ? and product.state = 0 and shop.isOpen = 1 and shop.state = 0 order by product.sort asc,product.addtime desc	 limit ?,?",new MapListHandler(),new Object[]{areaId,classId,Integer.valueOf(begin),Integer.valueOf(end)});
//					System.out.println("酒店的产品"+pros.toString());;
//				}
//			}



            JsonUtils.writeSuccessJson("查询成功", pros, response);
        } catch (SQLException e) {
            e.printStackTrace();
            JsonUtils.writeBeanFailJson("查询失败", response);
        }
    }
    /**
     * 获取日期
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    public void weekday(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        QueryRunner qr = new QueryRunner(C3p0DataSourceUtils.getDataSource());
        List<Map<String, Object>> weekday = null;
        try {
            weekday = qr.query("SELECT DATE_FORMAT(sdate,'%Y-%m-%d') as wdate,DAYOFWEEK(sdate) AS wday,IF(sdate<=DATE_FORMAT(NOW(),'%Y-%m-%d'),'1','3') AS state FROM sendDate order by sdate",new MapListHandler());
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Date now = new Date();
            //遍历找出第一个大于当前日期的选项
            for (Map<String, Object> item : weekday) {
                try {
                    Date wdate = sdf.parse((String)item.get("wdate"));
                    if (wdate.after(now)){
                        item.put("state","2");
                        break;
                    }
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
            JsonUtils.writeSuccessJson("查询成功", weekday, response);
        } catch (SQLException e) {
            e.printStackTrace();
            JsonUtils.writeBeanFailJson("查询失败", response);
        }
    }

	/**
	 * 酒店获取日期
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	public void hotelWeekday(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
		QueryRunner qr = new QueryRunner(C3p0DataSourceUtils.getDataSource());
		List<Map<String, Object>> weekday = null;
		try {
			weekday = qr.query("SELECT DATE_FORMAT(sdate,'%Y-%m-%d') as wdate,DAYOFWEEK(sdate) AS wday,IF(sdate<=DATE_FORMAT(NOW(),'%Y-%m-%d'),'1','3') AS state FROM t_hotel_senddate order by sdate",new MapListHandler());
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			Date now = new Date();
			//遍历找出第一个大于当前日期的选项
			for (Map<String, Object> item : weekday) {
				try {
					Date wdate = sdf.parse((String)item.get("wdate"));
					if (wdate.after(now)){
						item.put("state","2");
						break;
					}
				} catch (ParseException e) {
					e.printStackTrace();
				}
			}
			JsonUtils.writeSuccessJson("查询成功", weekday, response);
		} catch (SQLException e) {
			e.printStackTrace();
			JsonUtils.writeBeanFailJson("查询失败", response);
		}
	}
	
	public void comment(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try {
			String temp = request.getParameter("id");
			int goodsId = -1;
			try {
				goodsId = Integer.valueOf(temp);
			} catch (Exception e) {
				goodsId = -1;
				JsonUtils.writeListFailJson("查询失败!!", response);
				return;
			}
			String begin_s = request.getParameter("begin");
			String end_s = request.getParameter("end");
			int begin = 0;
			int end = 10;
			try {
				begin = Integer.valueOf(begin_s);
			} catch (Exception e) {
				begin = 0;
				e.printStackTrace();
			}
			try {
				end = Integer.valueOf(end_s);
			} catch (Exception e) {
				end = 0;
				e.printStackTrace();
			}
			List<com.zaofan.mobile.bean.Comment> datas = new ArrayList<>();
			com.zaofan.mobile.bean.Comment comment = null;
			List<Comment> comments = commentService.findProductComments(goodsId, begin, end);
			for (Comment item : comments) {
				comment = new com.zaofan.mobile.bean.Comment();
				BeanUtils.copyProperties(comment, item);
				if (comment.getIsReply() == 1) {
					Reply reply = replyService.findByCommentId(comment.getId());
					comment.setReply(reply);
				}
				if (comment.getUserPhoto() != null && !"".equals(comment.getUserPhoto())) {
					comment.setUserPhoto(UrlConstant.HOST_URL + comment.getUserPhoto());
				}
				datas.add(comment);
			}
			JsonUtils.writeSuccessJson("查询成功", datas, response);
		} catch (Exception e) {
			e.printStackTrace();
			JsonUtils.writeListFailJson("参数错误!!", response);
		}
		JsonUtils.writeListFailJson("查询失败!!", response);
	}

	public void findHotProduct(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try {
			String cityId = request.getParameter("cityId");
			int page = Integer.parseInt(request.getParameter("page"));
			List<Product> data = productService.findHotProduct(cityId, page);
			JsonUtils.writeSuccessJson("查询成功", data, response);
		}catch (Exception e){
			e.printStackTrace();
			JsonUtils.writeBeanFailJson("查询失败", response);
		}
	}

	public void findAllHotProduct(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try {
			String cityId = request.getParameter("cityId");
			String begin = request.getParameter("begin");
			String end = request.getParameter("end");
			List<Product> data = productService.findAllHotProduct(cityId,begin,end);
			JsonUtils.writeSuccessJson("查询成功", data, response);
		}catch (Exception e){
			e.printStackTrace();
			JsonUtils.writeBeanFailJson("查询失败", response);
		}
	}
	
}
